"""
基础模型类
提供公共字段和方法
"""
from sqlalchemy import Column, Integer, DateTime, String, Boolean
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.sql import func
from datetime import datetime
from typing import Any
from sqlalchemy.orm import DeclarativeBase

class Base(DeclarativeBase):
    """基础模型类"""
    
    id = Column(Integer, primary_key=True, index=True, comment="主键ID")
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), comment="更新时间")
    is_deleted = Column(Boolean, default=False, comment="是否删除")
    
    @declared_attr
    def __tablename__(cls) -> str:
        """将类名转换为表名"""
        import re
        # 将驼峰命名转换为下划线命名
        name = re.sub(r'(?<!^)(?=[A-Z])', '_', cls.__name__).lower()
        return name
    
    def to_dict(self) -> dict:
        """转换为字典"""
        result = {}
        for column in self.__table__.columns:
            value = getattr(self, column.name)
            if isinstance(value, datetime):
                value = value.isoformat()
            result[column.name] = value
        return result
    
    def update(self, **kwargs):
        """更新模型属性"""
        for key, value in kwargs.items():
            if hasattr(self, key):
                setattr(self, key, value)
    
    def soft_delete(self):
        """软删除"""
        self.is_deleted = True
    
    def restore(self):
        """恢复软删除"""
        self.is_deleted = False
    
    @classmethod
    def get_field_names(cls) -> list:
        """获取字段名列表"""
        return [column.name for column in cls.__table__.columns]
    
    @classmethod
    def get_required_fields(cls) -> list:
        """获取必填字段列表"""
        return [
            column.name for column in cls.__table__.columns 
            if not column.nullable and column.default is None
        ]


class TimestampMixin:
    """时间戳混入类"""
    
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), comment="更新时间")


class SoftDeleteMixin:
    """软删除混入类"""
    
    is_deleted = Column(Boolean, default=False, comment="是否删除")
    
    def soft_delete(self):
        """软删除"""
        self.is_deleted = True
    
    def restore(self):
        """恢复软删除"""
        self.is_deleted = False


class ActiveMixin:
    """激活状态混入类"""
    
    is_active = Column(Boolean, default=True, comment="是否激活")
    
    def activate(self):
        """激活"""
        self.is_active = True
    
    def deactivate(self):
        """停用"""
        self.is_active = False